package com.woniu.service.impl;

import com.woniu.dao.ActivityComplaintMapper;
import com.woniu.dao.ActivityMapper;
import com.woniu.dao.ActivityUserMapper;
import com.woniu.dao.CommunityOrderMapper;
import com.woniu.dto.ActivityDetail;
import com.woniu.dto.ActivityPost;
import com.woniu.dto.MyActivityPost;
import com.woniu.pojo.Activity;
import com.woniu.pojo.ActivityComplaint;
import com.woniu.pojo.ActivityUser;
import com.woniu.pojo.CommunityOrder;
import com.woniu.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityComplaintMapper activityComplaintMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityUserMapper activityUserMapper;
    @Autowired
    private CommunityOrderMapper communityOrderMapper;

    /**
     * 投诉活动
     * @param map 投诉数据
     */
    @Override
    public void save(Map<String, Object> map) {
        //构造一个新的投诉实体
        Integer userId = Integer.valueOf(map.get("userId").toString());
        String picPath = String.valueOf(map.get("picPath"));
        Integer activityId = Integer.valueOf(map.get("activityId").toString());
        String content = String.valueOf(map.get("content"));
        ActivityComplaint activityComplaint = new ActivityComplaint(userId,activityId,picPath,new Date(),content);
        activityComplaintMapper.insertSelective(activityComplaint);
    }

    /**
     * 发布活动
     * @param map 活动数据
     */
    @Override
    public void ActivitySave(Map<String, Object> map) {
        //构造一个活动实体,从前端获取数据
        Integer userId = Integer.valueOf(map.get("userId").toString());
        String picPath = String.valueOf(map.get("picPath"));
        Integer type = Integer.valueOf(map.get("type").toString());
        String title = String.valueOf(map.get("activityName"));
        Date startTime=null,endTime=null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = sdf.parse(map.get("startTime").toString());
            endTime = sdf.parse(map.get("endTime").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer statue = 0;
        Double money = Double.valueOf(map.get("money").toString());
        Integer peopelCount = 1;
        Integer maxCount = Integer.valueOf(map.get("maxCount").toString());
        Date createTime = new Date();
        String content = String.valueOf(map.get("content"));
        Activity activity = new Activity(userId,picPath,type,title,startTime,endTime,statue,money,peopelCount,maxCount,createTime,content);
        //保存活动到数据库
        Integer activityId = activityMapper.insertSelective(activity);
        System.out.println(activity.getId());
        //保存当前发布人到活动用户中间表中，即报名表
//        ActivityUser activityUser = new ActivityUser(activity.getId(),userId);
//        activityUserMapper.insertSelective(activityUser);
    }

    /**
     * 查找指定id的活动，同时判断用户类型，并封装成前端需要的数据
     * @param activityId
     * @param userId
     * @return
     */
    @Override
    public ActivityDetail findActivity(Integer activityId,Integer userId) {
        //前端需要的数据实体
        ActivityDetail activityDetail = new ActivityDetail();
        //活动信息
        Activity activity = activityMapper.selectByPrimaryKey(activityId);
        activityDetail.setActivity(activity);
        //活动发布用户名字
        String userName = activityUserMapper.selectNameById(activity.getCaUserId());
        activityDetail.setUserName(userName);
        //处理状态
        switch (activity.getCaStatus()){
            case 0:activityDetail.setStatus("未开始");break;
            case 1:activityDetail.setStatus("进行中");break;
            case 2:activityDetail.setStatus("已结束");
        }

        //查出该用户报名情况，这里大多针对付费活动（涉及退款操作），免费活动取消报名即刻成功，会删掉改用户信息
        ActivityUser activityUser = activityUserMapper.selectByIdAndUserId(activityId,userId);
        //对登录用户进行处理  cauSignStatus 0:申请报名，1：取消报名 2：取消中（退款），3：支付失败，需重新支付
        if(activity.getCaStatus()==2){
            activityDetail.setSignUp("活动已结束");
        }else if(userId==activity.getCaUserId()){
            //如果登录用户就是活动发布者
            activityDetail.setSignUp("报名详情");
        } else if(userId!=null && activityUser!=null){
            if((activity.getCaStatus()==1 || activity.getCaStatus()==0) && activityUser.getCauSignStatus()==0){
                activityDetail.setSignUp("申请中");
            }else if (activity.getCaStatus()==1 && activityUser.getCauSignStatus()==1){
                activityDetail.setSignUp("已报名");
            }else if(activity.getCaStatus()==0 && activityUser.getCauSignStatus()==1){
                activityDetail.setSignUp("取消报名");
            }else if(activity.getCaStatus()==0 && activityUser.getCauSignStatus()==2){
                activityDetail.setSignUp("取消中");
            }else if(activityUser.getCauSignStatus()==3){
                activityDetail.setSignUp("重新支付");
            }
        }else if(userId!=null && activityUser==null && activity.getCaPeopelCount()==activity.getCaMaxPeopleCount()){
            //用户未报名，活动未结束，但是报名人数已满
            activityDetail.setSignUp("报名已结束");
        }
        return activityDetail;
    }

    /**
     * 保存报名活动，用户id到报名表
     * @param activityId
     * @param userId
     */
    @Override
    public String saveSignUp(Integer activityId, Integer userId) {
        //保存订单号
        String coNum = "";
        Integer status = 0;
        //新增报名用户数据,判断是否是付费活动,0:免费，3：付费，付费需要创建订单
        Activity activity = activityMapper.selectByPrimaryKey(activityId);
        if(activity.getCaMoney()>0){
            //创建一个订单
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String num = simpleDateFormat.format(new Date())+"4"+userId;        //自定义订单编号，时间+类型+用户id
            CommunityOrder order = new CommunityOrder(userId,num,activity.getCaMoney(),0,new Date(),"活动订单",activityId);
            communityOrderMapper.insertSelective(order);
            coNum = num;
            status = 3;
        }
        //添加活动用户
        ActivityUser activityUser = new ActivityUser(activityId,userId,status);
        activityUserMapper.insertSelective(activityUser);
        return coNum;
    }

    /**
     * 取消指定用户的指定活动报名
     * @param activityId
     * @param userId
     */
    @Override
    public void deleteById(Integer activityId, Integer userId) {
        //判断是否是付费活动
        Activity activity = activityMapper.selectByPrimaryKey(activityId);
        //免费活动，直接取消，并删除该用户数据
        if(activity.getCaMoney()==0){
            activityUserMapper.deleteById(activityId,userId);
            //活动人数-1
            activity.setCaPeopelCount(activity.getCaPeopelCount()-1);
            activityMapper.updateByPrimaryKeySelective(activity);
        }else{
            ActivityUser activityUser = activityUserMapper.selectByIdAndUserId(activityId,userId);
            //设置报名状态为2，即申请退款
            activityUser.setCauSignStatus(2);
            activityUserMapper.updateByPrimaryKeySelective(activityUser);
        }

    }

    /**
     * 获取活动
     * @param type 活动类型
     * @param page 开始页面*10
     * @return
     */
    @Override
    public List<ActivityPost> findByType(Integer type, Integer page) {
        //判断活动类型，0：全部
        if(type==0){
            return activityMapper.selectByPage(page);
        }else{
            return activityMapper.selectByType(type,page);
        }
    }

    @Override
    public List<MyActivityPost> findUserById(Integer activityId) {
        List<MyActivityPost> myActivityPosts = activityUserMapper.selectByActivityId(activityId);
        for(MyActivityPost my:myActivityPosts){
            if(my.getCauSignStatus()==1){
                my.setSignUp("移除");
            }else if(my.getCauSignStatus()==2){
                my.setSignUp("退款");
            }
        }
        return myActivityPosts;
    }

    @Override
    public int updateSignUp(Integer activityId, Integer userId) {
        ActivityUser activityUser = activityUserMapper.selectByIdAndUserId(activityId,userId);
        activityUser.setCauSignStatus(1);
        activityUserMapper.updateByPrimaryKeySelective(activityUser);
        //同时活动人数+1
        Activity activity = activityMapper.selectByPrimaryKey(activityId);
        activity.setCaPeopelCount(activity.getCaPeopelCount()+1);
        activityMapper.updateByPrimaryKeySelective(activity);

        return activityUserMapper.updateByPrimaryKeySelective(activityUser);
    }

    @Override
    public int deleteByActivityIdAndUserId(Integer activityId, Integer userId) {
        //删除指定活动指定用户
       int count = activityUserMapper.deleteById(activityId,userId);
       if(count>0){
           //同时活动人数-1
           Activity activity = activityMapper.selectByPrimaryKey(activityId);
           activity.setCaPeopelCount(activity.getCaPeopelCount()-1);
           activityMapper.updateByPrimaryKeySelective(activity);
       }
        return count;
    }

    /**
     * 根据用户id和活动id查找订单编号
     * @param activityId
     * @param userId
     * @return
     */
    @Override
    public String findCoNum(Integer activityId, Integer userId) {
        //返回最新的一个订单号给前端，这里是id倒序查询的
        return communityOrderMapper.selectById(activityId,userId).get(0);
    }

    @Override
    @Cacheable(value = "activitys",key = "#act")
    public List<Activity> selectAll(String act) {
        System.out.println("查询数据库");
        return activityMapper.selectAll();
    }

    @Override
    @CacheEvict(value = "activitys",key = "#act")
    public void updateActivity(Activity activity,String act) {
        activityMapper.updateByPrimaryKeySelective(activity);
    }

    @Override
    public String selectContent(Integer activityId) {
        return activityMapper.selectByPrimaryKey(activityId).getCaContent();
    }

}
